package com.yx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.entity.Book;
import com.yx.entity.Category;
import com.yx.service.IBookService;
import com.yx.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yx
 * @since 2022-02-07
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService cs;
    @Autowired
    private IBookService bs;
    @GetMapping("/selectAll")
    public List<Category> selectAll(){
        List<Category> list = cs.list();
        List<Book> bookList = bs.list();
        list=list.stream().peek(cate->{
            final long count = bookList.stream().filter((book) -> book.getCid() == cate.getCategoryId()).count();
            cate.setCount(count);
        }).collect(Collectors.toList());
        return list;
    }
    @PostMapping("/add")
    public void add(@RequestBody Category category){

        cs.save(category);
    }
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id") int id){
        QueryWrapper<Book> wrapper=new QueryWrapper<>();
        wrapper.eq("cid",id);
        bs.remove(wrapper);
        cs.removeById(id);
    }
}

